<script lang="ts">
  import { goto } from "$app/navigation";
  import { page } from "$app/state";
  import { boardStore } from "$lib/stores/board.svelte";
  import { getBoardPath } from "$lib/utils/consts";
  import { Tabs } from "@skeletonlabs/skeleton-svelte";
  import CreateDrawModal from "$lib/components/modal/board/draw/CreateDrawModal.svelte";
  import type { DrawInfo } from "$lib/api/board/board_draw";
  import ViewDrawPermModal from "$lib/components/modal/board/draw/ViewDrawPermModal.svelte";

  let { children } = $props();

  let curTab = $state("chat" as "chat" | "drawlist" | "info");
  let showCreateDrawModal = $state(false);

  let viewPermDrawInfo = $state(null as null | DrawInfo);

  $effect(() => {
    if (page.url.pathname.endsWith("chat")) {
      curTab = "chat";
    } else if (page.url.pathname.endsWith("drawlist")) {
      curTab = "drawlist";
    } else if (page.url.pathname.endsWith("info")) {
      curTab = "info";
    }
  });
</script>

<div class="h-[calc(100vh-50px)] overflow-y-hidden p-2 pr-0 relative">
  <div class="absolute right-[10px] flex gap-x-4 items-center">
    {#if curTab == "drawlist" && boardStore.curWebBoard?.myMember?.admin == true}
      <button
        type="button"
        class="btn preset-filled-primary-900-100 rounded-[10px]"
        onclick={() => (showCreateDrawModal = true)}
      >
        新建话题
      </button>
    {:else if curTab == "chat" && boardStore.curWebBoard?.myMember?.admin == true}
      <button
        type="button"
        class="btn preset-filled-primary-900-100 rounded-[10px]"
        onclick={() => (showCreateDrawModal = true)}
      >
        新建话题
      </button>
    {/if}
  </div>
  <Tabs
    value={curTab}
    onValueChange={(detail) =>
      goto(
        getBoardPath(
          boardStore.curBoardId,
          detail.value as "chat" | "drawlist" | "info",
        ),
      )}
    listMargin="m-0"
  >
    {#snippet list()}
      <Tabs.Control value="chat">沟通</Tabs.Control>
      <Tabs.Control value="drawlist">话题</Tabs.Control>
      <Tabs.Control value="info">信息</Tabs.Control>
    {/snippet}
    {#snippet content()}
      {@render children()}
    {/snippet}
  </Tabs>
</div>

<div class="absolute -left-[10000px]">
  {#if showCreateDrawModal}
    <CreateDrawModal onClose={() => (showCreateDrawModal = false)} />
  {/if}
  {#if viewPermDrawInfo != null}
    <ViewDrawPermModal
      boardId={boardStore.curBoardId}
      drawInfo={viewPermDrawInfo}
      canEdit={boardStore.curWebBoard?.myMember?.admin == true}
      onClose={() => (viewPermDrawInfo = null)}
    />
  {/if}
</div>
